import React from 'react'
// ===================================================================== 
import TableTitle from '../js/table-title'
// ===================================================================== Cols
import Cols44011 from '../js/table/11'
import Cols44013 from '../js/table/13'
import Cols44014 from '../js/table/14'
import Cols44015 from '../js/table/15'
import Cols99 from '../js/table/99'
import Cols100 from '../js/table/100'
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== antd
const Table 	= $Lazy.state(()=>import('@antd/table'))
const Button 	= $Lazy.load(()=>import('@antd/button'))
const Drawer 	= $Lazy.hook(()=>import('@antd/drawer'))
const Box 		= $Lazy.load(()=>import('#tp/box/box'))
const $cache 	= $Lazy.file(()=>import('#private/cache-api'))
// 显示标本异常
const SpecimensModal= $Lazy.state(()=>import('@views/testing-center/js/controls/modal/specimens-modal'), 1)
// const PositiveModal= $Lazy.state(()=>import('@views/testing-center/js/controls/modal/positive-modal'), 1)
// ===================================================================== data
// 下一页的特殊page
const nextPageIndex = [9, 19, 49, 99, 149, 199, 299, 499, 599, 999, 1999, 4999]
// 参考范围符号选择
const changeSymbol = value => {
	const data = [
		{ t1: '>', t2: '<' },
		{ t1: '≥', t2: '≤' },
		{ t1: '>=', t2: '<=' },
		{ t1: '<', t2: '>' },
		{ t1: '≤', t2: '≥' },
		{ t1: '<=', t2: '>=' }
	]
	let s = data.filter(i => i.t1 === value)
	if (s && s.length > 0) {
		return s[0].t2
	} else {
		return value	// 如果不需要转换就直接显示原来的符号
	}
}
// ===================================================================== 
class Index extends React.Component{
	state = { 
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		cols:[],
		posData:[],
		stack:{},
		key: 0
	}
	rows = {}
	index = null	// 选中数据的位置
	// 新增甲状腺岗 20211102 耿琰
	componentDidMount(){
		this.getSpecType()
		let cols = []
		const { query, result_model, BingLiMode, way } = this.props.top
		this.queryModel = query
		if([44011, 44012, 44020].includes(result_model)){
			cols = Cols44011.call(this)
		}else if([44013, 44022, 44021,44008,44029,44030,44032,44032,44033].includes(result_model)){
			cols = Cols44013.call(this)
		}else if([44014, 44027, 44028,44015,44016,44017,44019,44024,44025].includes(result_model)){
			cols = Cols44014.call(this)
		}else if([44015, 44018, 44031 ].includes(result_model)){
			cols = Cols44015.call(this)
		}
		this.cols = cols[result_model]
		this.isBingLiMode = BingLiMode.includes(result_model)
		if(way === 1 && !this.isBingLiMode){
			this.cols = this.props.child ? Cols100.call(this) : Cols99.call(this)
		}
		
		window.onRefresh = () => {
			this.props?.searchRef?.()?.onRefresh?.()
		}
		this.setState({ cols: this.cols })
	}
	
	componentWillUnmount(){
		this.setState = () => false
	}
	// 加载表格数据
	fetch = param => {
		const { parent, child, top } = this.props
		const { project_id, result_model } = param
		
		if(!project_id || !result_model){ return false }
		let api = 'ts-report-card/index'
		if(top.way && !this.isBingLiMode && parent) api = 'ts-report-card/parentKindLists'
		if(!child){
			return $fn.fetch.call(this, api, {
				param,
				callback: data=>{
					if (top.way && !this.isBingLiMode) {
						if (data.items?.length) {
							this.index != null && this.nextData()
						} else {
							this.index = null
						}
					}
					const stack = data.stat ? data.stat : {}
					this.setState({ stack })
				},
				isIndex: 1
			})
		}
	}
	empty = () => {
		this.index = null
		this.setState({ data: []})
	}
	// 加载子项目
	fetchChild = ({spec_code, parent_kind_id}) => {
		let { key } = this.state
		this.setState({key: key++})
		const { project_id, result_model } = this.props.top.query
		if(!project_id || !result_model){ return false }
		const param = { ...this.props.top.query,...this.props.top.searchRef.model, spec_code, parent_kind_id }
		return $fn.fetch.call(this,'ts-report-card/childKindLists', { param, paging: 'get', isIndex: 1, 
			// callback: data => {
			// 	if (this.props.top) {
			// 		if (data.items?.length) {
			// 			this.index != null && this.nextData()
			// 		} else {
			// 			this.index = null
			// 		}
			// 	}
			// }
		})
	}
	getSpecType = () => {
		// 获取阳性颜色
		$cache.then( async f => {
			const posData = await f.getCache({ api:'common/getColorResult' })
			const sampleTypeData = await f.getDisCache({ code: 2000 })
			this.setState({ posData, sampleTypeData })
		})
	}
	// 动态设置 Cols
	getCols = status => {
		let cols = $fn.deepCopy(this.cols)
		// 新增甲状腺岗 20211102 耿琰
		if(status !== 45007 && status !== 45008 && status !== 45032){
			cols = cols.filter(v => v.dataIndex !== 'status_abnormal_name')
		}
		this.setState({ cols })
	}
	
	// 获取信息
	getInfo = uuid => {
		const { result_model, status } = this.paramModel
		const { parent, top } = this.props
		const param = { uuid, result_model, status }
		if(!uuid) return
		if (top.way && !this.isBingLiMode) {
			if (parent) {
				param['check_view_mode'] = 1
				this.props.personRef().loading(true)
			} else {
				this.props.resultRef().loading(true)
			}
		} else {
			this.props.personRef().loading(true)
			this.props.resultRef().loading(true)
		}
		return $http.submit(this, 'ts-report-card/info',{ 
			param, dataName:null, loading:false, isPull:true,
			onEnd:()=>{
				this.props.personRef().loading(false)
				this.props.resultRef().loading(false)
			}
		}).then(data=>{
			if (top.way && !this.isBingLiMode) {
				if (parent) {
					// 人员详情
					this.props.personRef().load(data)
				} else {
					// 结果
					this.props.resultRef().load({info:data, rows:this.state.selectedRows, query:this.paramModel})
				}
			} else {
				this.props.personRef().load(data)
				this.props.resultRef().load({info:data, rows:this.state.selectedRows, query:this.paramModel})
			}
			this.props.btnGroupRef().getInfo(data)
			this.info = data
		})
	}
	
	getBaseInfo = async () => {
		const { result_model, status } = this.paramModel
		const { selectedRows } = this.state
		const { uuid } = selectedRows[selectedRows.length - 1]
		const { parent, top } = this.props
		const param = { uuid, result_model, status }
		if(!uuid) return
		if (top.way && !this.isBingLiMode && parent) {
			param['check_view_mode'] = 1
		}
		return $http.submit(this, 'ts-report-card/info',{ param, dataName:null, loading:false, isPull:true })
	}
	
	onRefreshInfo = () => {
		const { selectedKeys } = this.state
		const uuid = selectedKeys[selectedKeys.length -1]
		this.getInfo(uuid)
	}
	
	onRefresh = (param) => this.props.searchRef().onRefresh(param)
	onSubmit = param => this.props.searchRef().onSubmit(param)
	
	paramModel = { }
	
	change = param => {
		this.paramModel = param
		this.queryModel.status = param.status
		this.getCols(param.status)
		if(this.props.child) {
			return this.fetchChild(this.rows)
		} else {
			return this.fetch(param)
		}
	}
	
	FetchFirst = param => {
		this.paramModel = param
		this.queryModel.status = param.status
		this.getCols(param.status)
		/* 2021-09-27 j+2 默认加载 */
		// window.isInit && this.fetch(param) 
		this.fetch(param)
	}
	
	clear = (status) => {
		$fn.clearKeys.call(this)
		const query = this.queryModel
		this.props.btnGroupRef().setKeys( { selectedKeys:[], selectedRows:[], info:{}, query, mode:query.result_model  } )
		this.props.resultRef().clear(status)
	}
	// 重置
	reset = () => {
		let { key } = this.state
		this.clear()
		key++
		this.setState({ key })
		this.crossRef?.clear?.()
		this.reverseRef?.clear?.()
		this.props.btnGroupRef().getCrossPageSubmit(0)
	}
	// 加载下一条数据
	nextData = ()=>{
		const { parent, tableRef2 } = this.props
		const { pag } = this.state
		if (nextPageIndex.includes(this.index) && this.index + 1 === pag.pageSize && parent) {
			this.index = 0
			this.setState({pag: { ...pag, current: pag.current + 1 }}, () => this.fetch())
			return
		}
		const rows = this.state.data[this.index] ?? this.state.data[this.state.data.length - 1]
		this.setState({selectedKeys: [rows.uuid], selectedRows: [rows]}, () => {
			const { data, selectedKeys, selectedRows, pagingLoading } = this.state
			const query = this.queryModel
			this.rows = rows
			this.getInfo(rows.uuid)
			this.props.resultRef().xiFaSend(selectedRows.experiment_num)
			this.props.btnGroupRef().setKeys( { selectedKeys, selectedRows, data, pagingLoading, info:this.info, query, ...this.paramModel, mode:query.result_model  } )
			parent && tableRef2?.()?.fetchChild(rows)
		})
	}
	
	render(){
		const { data, posData, selectedKeys, selectedRows, submitLoading, cols, pag, pagingLoading, stack, reference_range, key } = this.state
		const { child, tableRef2, tableRef1 } = this.props
		const { isEntrust, result_model, way, btnGroupRef} = this.props.top
		return (
			<>
				<Box
					title				= '项目列表'
					className			= 'h ex project-list' 
					contentClassName	= 'fv pt10'
					flex 
					titleSuffix 		= {
						<>
							{
								!child && (
									[44016, 44014, 44017, 44019, 44024, 44025, 44027, 44028, 44015, 44018, 44031].includes(result_model) &&  <TableTitle.StatusComponent data={stack} isEntrust={isEntrust} key={key} onDoubleClick={ icon_type =>{
										this.props.searchRef().onSubmit({ icon_type })
									}}/>
								)
							}
						</>
					}
					titlePrefix			= { way && !this.isBingLiMode ? child && TableTitle.TitlePrefixComponent.call(this) : TableTitle.TitlePrefixComponent.call(this) }
					ref					= 'listRef'
					full
				>
					{/* 表格 */}
					<Table
						cols			= { cols }
						data 			= { data }
						loading 		= { pagingLoading  }
						onRef 			= { ref=>this.table=ref }
						pag				= { pag }
						// isIndex
						selectedKeys	= { selectedKeys }
						selectedRows	= { selectedRows }
						// isInit 			= { $fn.isValid(parent) ? window.isInit : null }	/* 2021-09-27 j+2 默认加载 */
						onChange		= { (current, pageSize)=>{
							this.props.searchRef().pageChange({ pageSize, current })
							if( this.clearKeys !== false ){ $fn.clearKeys.call(this) }
						} }
						rowSelect		= { way && !this.isBingLiMode ? false : true }
						onSelect		= { (selectedKeys, selectedRows) =>  {
							this.index = selectedRows[0]?.index
							if(way && !this.isBingLiMode){			// 分栏操作只操作一个表格  2021-9-9 --马婷
								if(tableRef2){		// 左边表格
									btnGroupRef.rowsType = 1
									tableRef2?.()?.setState({selectedKeys:[],selectedRows:[]})
								}else{				// 右边表格
									btnGroupRef.rowsType = 2
									tableRef1?.()?.setState({selectedKeys:[],selectedRows:[]})
								}
							}
							$fn.setKeys.call(this,selectedKeys,selectedRows)
							const query = this.queryModel
							this.props.btnGroupRef().setKeys( { selectedKeys, selectedRows, data, pagingLoading, info:this.info, query, ...this.paramModel, mode:query.result_model  } )
						}}
						onSort			= { value => this.props.searchRef().onSort({value, isTable: tableRef2 ? 1 : 0}) }
						// disabled		= { submitLoading }
						isDragWidth		= { !child }
						setHeader		= { way && !this.isBingLiMode ? child : true   }
						sort			= { true }
						type 			= { 'checkbox' }
						wrapClassName	= 'mlr5'
						space 			= 'h5'
						split 			= {this.isBingLiMode}
						onRow 			= { rows => {
							this.rows = rows
							this.getInfo(rows.uuid)
							this.props.resultRef().xiFaSend(rows.experiment_num)
							if(way && !this.isBingLiMode){
								const query = this.queryModel
								const { selectedKeys: keys1, selectedRows: rows1 } = this.props.top?.tableRef?.state
								const { selectedKeys: keys2, selectedRows: rows2 } = this.props.top?.tableRef2?.state
								let selectedKeys = keys1.length ? keys1 : keys2
								let selectedRows = rows1.length ? rows1 : rows2
								if(tableRef2){
									tableRef2?.()?.setState({selectedKeys:[],selectedRows:[]})
									tableRef2?.()?.fetchChild(rows)
									if (!keys1.length) {
										selectedKeys = []
										selectedRows = []
									}
								}
								this.props.btnGroupRef().setKeys( { selectedKeys, selectedRows, data, pagingLoading, info:this.info, query, ...this.paramModel, mode:query.result_model  } )
							}
						}}
						onRowClass 		= { ({ result, result1, result_type, forms={}, currentClass })=>{
							let className = 'bcf'
							if(forms.type === 'text'){
								if(result.includes('阳性')){
									className = 'row-fb8787'
								}else if(result.includes('弱阳')){
									className = 'row-e24747'
								}
							}else{
								if($fn.hasArray(posData)){
									posData.forEach( v => {
										const [text, code] = v.range
										if(text.includes(result1) || code.includes(result1) || text.includes(result) || (['1203', '1205'].includes(result_type) && code.includes(result))) {
											className = v.class_name
										}
									})
								}
							}
							return className + ' ' + (currentClass || '')
						} }
					/>
					<div className='fxmj tbor1 bcf rel i10' style={{padding:5}}>
						<Button label='显示异常标本' disabled={!$fn.hasArray(selectedKeys)} loading={submitLoading} onClick={()=>{
							let rowsType
							if(way && !this.isBingLiMode){			// 显示异常标本分别操作左右表格  2021-9-9 --马婷
								rowsType = tableRef2 ? 1 : 2		// 1:左边表格，2:右边表格
							}
							this.specimensModalModal.open({ dmodel: this.paramModel.result_model, status: this.paramModel.status, uuid:selectedKeys[selectedKeys.length-1] }, this.getBaseInfo, rowsType)
						}} />
						<div className='ml10 g9'>当前选中 <b className='f14 c0'>{selectedKeys.length}</b> 条数据</div>
					</div>
					<Drawer title='参考范围' ref={ ref => this.drawer = ref?.refs?.ref } width='25%'>
						<ul>
							{
								$fn.hasArray(reference_range) && reference_range.reverse().map((v,i)=>{
									const sexName = { '45701':'男', '45702':'女', '':'其它' }
									return (
										<li className='fx mb10 f12 g6 lh22' key={i}>
											<div className='tr mr30' style={{width:25}}>{sexName[v.sex]}</div>
											<dl className='ex'>
												<dd>{v.age_min_val} {changeSymbol(v.age_min_type_name)} 年龄值 {v.age_max_type_name} {v.age_max_val}</dd>
												<dd>{v.reference_min_val} {changeSymbol(v.reference_min_type_name)} 参考范围 {v.reference_max_type_name} {v.reference_max_val}</dd>
												<dd>{v.crisis_min_val} {changeSymbol(v.crisis_max_type_name)} 危机值范围 {v.crisis_max_type_name} {v.crisis_max_val}</dd>
											</dl>
										</li>
									)
								})
							}
						</ul>
					</Drawer>
				</Box>
				{/* 显示标本异常 */}
				<SpecimensModal onRef={ref=>this.specimensModalModal=ref} onRefresh={this.onRefresh} />
				{/* 阳性列表 */}
				{/* <PositiveModal onRef={ref=>this.positiveModalRef=ref}/> */}
				
			</>
		)
	}
}

export default Index